/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package cn.newtest.bi.collection.formula.runtime;

import groovy.lang.GroovyObject;

import java.util.List;

import net.risesoft.risebi.collection.groovy.GroovyLoader;
import net.risesoft.risebi.collection.model.Formula;
import net.risesoft.risebi.collection.model.ReportData;
import net.risesoft.risebi.collection.model.ReportInstance;
import net.risesoft.risebi.collection.model.Template;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.TemplateManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 *
 * @author <a href="mailto: chenjian@risesoft.net">陈健</a>
 * @version $Revision$
 * 
 */
@Repository(value="calculator")
public class DefaultCalculator implements Calculator {
	
	private GroovyLoader groovyLoader;
	private TemplateManager templateManager;

	@Autowired
	public void setTemplateManager(TemplateManager templateManager) {
		this.templateManager = templateManager;
	}

	@Autowired
	public void setGroovyLoader(GroovyLoader groovyLoader) {
		this.groovyLoader = groovyLoader;
	}

	/*
	 * (non-Javadoc)
	 * @see net.risesoft.risebi.collection.formula.runtime.Calculator#doCalculate(java.lang.String, net.risesoft.risebi.collection.model.ReportData, int, net.risesoft.risebi.collection.model.User)
	 */
	public void doCalculate(String templateGuid, ReportData rd,int executePoint,User user,ReportInstance ri) throws Exception {
//		String templateFilePath = FilePersistLocator.getFilePersistLocator(SystemConstants.REPORT_TEMPLATEFILE);
//		templateFilePath += templateGuid+"/";
//		String fileName = templateFilePath + "G"+templateGuid+"Calculate.groovy";
//		
//		File file = new File(fileName);
//		if(!file.exists())
//			return;
		
		GroovyObject go = groovyLoader.getGroovyObject(templateGuid,"calculate");
		
		if(go==null)
			return;
		
		go.setProperty("ri", ri);
		go.setProperty("rd", rd);
		go.setProperty("user", user);
		
		Template template = (Template) templateManager.getObject(Template.class, templateGuid);
		List<Formula> formulas = template.getFormulas();
		for(int i=0;i<formulas.size();i++){
			Formula formula = formulas.get(i);
			if(formula.getType()==Formula.TYPE_JISUANGONGSHI){
				if(formula.getExecutePoint()>=executePoint){
					String formulaName = "f"+formula.getGuid();
					Object[] args = {};
			        go.invokeMethod(formulaName, args);
				}
			}
		}
	}

}
